package cn.codergege.springmvc.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.codergege.springmvc.model.Department;
import cn.codergege.springmvc.model.Employee;
import cn.codergege.springmvc.service.DepartmentService;
import cn.codergege.springmvc.service.EmployeeService;

@Controller
@RequestMapping("/employee")
public class EmployeeHandler {
	private final Logger log = LoggerFactory.getLogger(EmployeeHandler.class);
	@Resource
	private EmployeeService employeeService;
	@Resource
	private DepartmentService departmentService;

	@ModelAttribute
	public void queryEmployee(
			@RequestParam(value = "id", required = false) Integer id,
			Map<String, Object> map) {
		// 如果 id 不为空, 说明是 PUT 请求, 需要从数据库中取出原始值.
		if(id != null) {
			try {
				Employee employee = employeeService.getById(id);
				map.put("employee", employee);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("----> " + e.getLocalizedMessage());
				// todo 转异常页面
			}
		}
	}
	
	@RequestMapping("/employees")
	public String list(Map<String, Object> map) {
		try {
			List<Employee> employees = employeeService.getAll();
			map.put("employees", employees);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("----> " + e.getLocalizedMessage());
		}
		return "forward:/WEB-INF/employee/list.jsp";
	}

	@RequestMapping("/employee")
	public String add(Map<String, Object> map) {
		fillMap(map);
		Employee employee = new Employee();
		map.put("employee", employee);

		return "forward:/WEB-INF/employee/add.jsp";
	}

	@RequestMapping(value = "/employee", method = RequestMethod.POST)
	public String add(@Valid Employee employee, BindingResult result, Map<String, Object> map) {
		// 验证有错误
		if (result.getErrorCount() > 0) {
			for (FieldError error : result.getFieldErrors()) {
				log.info("----> " + error.getField() + ":" + error.getDefaultMessage());
			}
			// 不需要 new Employee() 了 
			fillMap(map);
			return "forward:/WEB-INF/employee/add.jsp";
		}
		// 验证成功
		try {
			employeeService.add(employee);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("----> " + e.getLocalizedMessage());
			fillMap(map);
			return "forward:/WEB-INF/employee/add.jsp";
		}
		return "redirect:/employee/employees";
	}
	
	@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") Integer id) {
		try {
			employeeService.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getLocalizedMessage());
		}
		return "redirect:/employee/employees";
	}

	// update employee
	
	@RequestMapping("/employee/{id}")
	public String update(@PathVariable("id") Integer id, Map<String, Object> map) {
		fillMap(map);
		try {
			Employee employee = employeeService.getById(id);
			map.put("employee", employee);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("----> " + e.getLocalizedMessage());
			// todo 转异常页面
		}
		return "forward:/WEB-INF/employee/update.jsp";
	}
	@RequestMapping(value = "/employee", method = RequestMethod.PUT)
	public String update(Employee employee,
			BindingResult result,
			Map<String, Object> map) {
		// 验证失败
		if(result.getErrorCount() > 0) {
			for(FieldError error: result.getFieldErrors()) {
				log.info("----> " + error.getDefaultMessage());
			}
			fillMap(map);
			map.put("employee", employee);
			return "forward:/WEB-INF/employee/update.jsp";
		}
		// 验证通过
		try {
			employeeService.update(employee);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("----> " + e.getLocalizedMessage());
			fillMap(map);
			map.put("employee", employee);
			return "forward:/WEB-INF/employee/update.jsp";
		}
		return "redirect:/employee/employees";
	}
	private void fillMap(Map<String, Object> map) {
		Map<Integer, Object> genders = new HashMap<Integer, Object>();
		genders.put(1, "男");
		genders.put(0, "女");
		List<Department> departments = null;
		try {
			departments = departmentService.getAll();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("----> " + e.getLocalizedMessage());
		}
		map.put("genders", genders);
		map.put("departments", departments);
	}
}
